#include "StdAfx.h"
#include "GMUrlAddressHistory.h"
#include "GMUtilManager.h"

#include "Markup.h"

#define HISTORY_URL_COUNT  20

CGMUrlAddressHistory::CGMUrlAddressHistory(void)
{
	m_HistroyFilePath = CGMUtilManager::GetGMAppExistPath();
	m_HistroyFilePath = m_HistroyFilePath + TEXT("Res\\History.xml");
}

CGMUrlAddressHistory::~CGMUrlAddressHistory(void)
{
}

BOOL CGMUrlAddressHistory::LoadHistoryUrls()
{
	CMarkup cGmXml;
	if (cGmXml.Load(m_HistroyFilePath) == false)
	{
		ASSERT(FALSE);
		return FALSE;
	}
	cGmXml.ResetMainPos();
	if (cGmXml.FindElem(TEXT("History")) == false)
	{
		ASSERT(FALSE);
		return FALSE;
	}
	cGmXml.IntoElem();

	while (cGmXml.FindElem(TEXT("url")))
	{
		CString strUrlOld = cGmXml.GetData();
		CString strUrlNew = cGmXml.UnescapeText(strUrlOld);

		m_HistoryUrls.Add(strUrlNew);

	}

	return TRUE;
}
BOOL CGMUrlAddressHistory::SaveHistoryUrls()
{
	CMarkup cGmXml;
	if (cGmXml.Load(m_HistroyFilePath) == false)
	{
		ASSERT(FALSE);
		return FALSE;
	}
	cGmXml.ResetMainPos();
	if (cGmXml.FindElem(TEXT("History")) == false)
	{
		ASSERT(FALSE);
		return FALSE;
	}
	cGmXml.IntoElem();
	
	while (cGmXml.FindElem(TEXT("url")))
	{	
		cGmXml.RemoveElem();
	}


	int nCount = m_HistoryUrls.GetCount();
	for (int index = 0;index < nCount;index++)
	{
		CString strElement = m_HistoryUrls.GetAt(index);

		CString strDest = cGmXml.EscapeText(strElement);

		cGmXml.AddElem(TEXT("url"),strDest);

	}
	cGmXml.Save(m_HistroyFilePath);


	return TRUE;
}

void CGMUrlAddressHistory::AddNewUrl(CString strUrl)
{
	BOOL bExist = CheckURLExist(strUrl);
	if (bExist)
	{
		return;
	}
	int nCount = m_HistoryUrls.GetCount();
	if (nCount > HISTORY_URL_COUNT)
	{
		m_HistoryUrls.RemoveAt(nCount - 1);
	}

	m_HistoryUrls.InsertAt(0,strUrl);
}

int CGMUrlAddressHistory::GetHistoryCount() const
{
	return m_HistoryUrls.GetCount();
}
const CString CGMUrlAddressHistory::GetUrlByIndex(int index) const
{
	int nCount = m_HistoryUrls.GetCount();
	ASSERT(index >= 0 && index <= nCount);

	if (index < 0 || index >= nCount)
	{
		return CString("");
	}

	return m_HistoryUrls.GetAt(index);
}

BOOL CGMUrlAddressHistory::CheckURLExist(const CString strUrl) const
{
	int nCount = m_HistoryUrls.GetCount();
	for (int index = 0;index < nCount;index++)
	{
		CString strElement = m_HistoryUrls.GetAt(index);
		if (strElement.CompareNoCase(strUrl) == 0)
		{
			return TRUE;
		}
	}
	return FALSE;
}

